<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证码</title>
</head>
    
    <style>
        input {
            height: 30px;
            vertical-align: middle;
        }

        span {
            display: inline-block;
            padding: 0px 10px;
            line-height: 30px;
            height: 30px;
            background: pink;
            vertical-align: middle;
            color: #fff;
            user-select: none;
        }
    </style>

    <script src="../utils.js"></script>
</head>

<body>
    <input type="text" id="val">
    <span id="code"></span>
    <input type="button" value="验证" id="btn">
    <script>
        // 生成4位数的随机数
        // var num = randomNum(1000, 9999);
        // 通过循环生成 4个一位数的随机数，突然拼接起来
        // 把生成验证码的代码封装
        function createCode() {
            var num = '';
            for (var i = 0; i < 4; i++) {
                num += randomNum(0, 9);
            }
            return num;
        }
        code.innerHTML = createCode();


        btn.onclick = function () {
            if (val.value === code.innerHTML) {
                alert('验证成功')
            } else {
                alert('验证失败');
                // 当验证失败的时候重新刷新验证码
                code.innerHTML = createCode();
                // 把输入验证码的输入框清空
                val.value = '';
            }
        }
        code.onclick=function(){
            code.innerHTML=randomNum(1000,9999)
        }



    </script>
</body>
</html>